package booksManagement;

import java.util.List;
import exceptions.*;
import booksManagement.Media;
import jpaUtils.JPAUtil;
import javax.persistence.EntityManager;

/**
 * 
 * @author GPIRAUX
 * 27/04/2012
 *
 */
public class MediaDAO
{
	public boolean isEmpty(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		if (entityManager.createNamedQuery("findAllMedias").getResultList().isEmpty())
			return true;
		else
			return false;	
	}





	/**
	 */
	public List<Media> getContent(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		return ((List<Media>)entityManager.createNamedQuery("findAllMedias").getResultList());
	}






	public boolean add(Media media){
			EntityManager entityManager=JPAUtil.getEntityManager();
	try{
				entityManager.persist(media);
			} catch (Exception e) {
				System.err.println("Problem when saving");
				e.printStackTrace();
				return false;
			}
			return true;
		}








		public String toString(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			String result="";
			List<Media> theMedias = (List<Media>) entityManager.createNamedQuery("findAllMedias").getResultList();
			for (Media m : theMedias)
				result += m.toString()+ "\n";
					return result;
		}







		/**
		 */
		public Media get(String mediaId) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			Media m = (Media) entityManager.find(Media.class, mediaId);
			if (m ==null) throw new BookExistsException();
			else return m;
		}






		/**
		 */
		public long size(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			return (entityManager.createNamedQuery("findAllMedias").getResultList().size());
		}






		/**
		 */
		public boolean remove(Media media) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			if (media== null) 
				throw new BookExistsException(); 
			else 
				try{
					entityManager.remove(media);
				} catch (Exception pe) {
					System.err.println("problem when deleting an entity ");
					pe.printStackTrace();
					return false;
				}
			return true;	
		}





			
			/**
			 */
			public boolean contains(Media media) throws BookExistsException {
				EntityManager entityManager=JPAUtil.getEntityManager();
				if (media == null) throw new BookExistsException();
				Media m = (Media) entityManager.find(Media.class, media.getIsbn_isan());
				if (m ==null) return false;
				else return m.equals(media);	
					
			}


}
